//
//  DJViewPager.swift
//  Pods
//
//  Created by 炬鑫 on 2017/3/13.
//
//

import UIKit

extension UIColor {
    class var defaultSelectedColor:UIColor {
        get {
            return UIColor(colorLiteralRed: 12/255.0, green: 134/255.0, blue: 237/255.0, alpha: 1)
        }
    }
}

//外部想要引用到，需要加上Public关键字修饰
public class DJViewPager: UIView {
    
    public typealias SelectedBlock = (_ viewPager:Any, _ index:Int) -> Void

    var scrollView:UIScrollView!
    var pageControl:UIView!
    
    /// 设置viewPager是否允许滚动 默认支持
    var enableScroll = true
    
    /// 当前选择的菜单索引
    var selectedIndex = 0 {
        didSet {
            if block != nil {
                block(self, selectedIndex)
            }
            for i in 0..<pageNum {
                let btn = viewWithTag(i+100) as! UIButton
                btn.backgroundColor = tagBgColor
                btn.isSelected = false
            }

            let btn = viewWithTag(selectedIndex + 100) as! UIButton
            let selectedLabel = pageControl.viewWithTag(300) as! UILabel
            btn.backgroundColor = tabSelectedBgColor
            btn.isSelected = true

            if showAnimation {
                UIView.animate(withDuration: 0.3, animations: {
                    selectedLabel.frame.origin.x = btn.frame.origin.x
                })
            } else {
                selectedLabel.frame.origin.x = btn.frame.origin.x
            }
        }
    }
    
    /// 菜单按钮背景属性
    var tagBgColor = UIColor.white
    var tabSelectedBgColor = UIColor.white {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /// 菜单按钮的标题颜色属性
    var tabArrowBgColor = UIColor(colorLiteralRed: 204/255.0, green: 208/255.0, blue: 210/255.0, alpha: 1)
    var tabSelectedArrowBgColor = UIColor.defaultSelectedColor
    
    /// 菜单按钮的标题颜色属性
    var tabTitleColor = UIColor.defaultSelectedColor
    var tabSelectedTitleColor = UIColor.defaultSelectedColor
    
    /// 是否显示垂直分割线  默认显示
    var showVLine = true
    
    /// 是否显示底部横线  默认显示
    var showBottomLine = true
    
    /// 选中状态是否显示底部横线  默认显示
    var showSelectedBottomLine = true
    
    /// 是否显示垂直分割线  默认显示
    var showAnimation = true
    
    /// 菜单标题
    private let titleArray:[String]
    
    /// 视图
    private let views:[Any]
    
    public var block:SelectedBlock!

    private var pageNum = 0
    /*
    菜单标题左侧的小图标
    */
    private var titleIconsArray = [UIImage]()
    /*
    菜单被选中时左侧的小图标
    */
    private var selectedIconsArray = [UIImage]()
    
    /// 菜单右上角的小红点显示的数量
    public var tipsCountArray = [Int]() {
        didSet {
            setNeedsDisplay()
        }
    }
    
   required public init(frame:CGRect, titles:[String], views:[Any]) {
        self.views = views
        titleArray = titles
        super.init(frame: frame)
        backgroundColor = .gray
        isUserInteractionEnabled = true
    }

    required public init(frame:CGRect, titles:[String], icons:[UIImage], selectedIcons:[UIImage]?, views:[Any]) {
        self.views = views
        titleArray = titles
        titleIconsArray = icons
        if selectedIcons != nil {
            selectedIconsArray = selectedIcons!
        }
        super.init(frame:frame)
        backgroundColor = .gray
        isUserInteractionEnabled = true
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func draw(_ rect: CGRect) {
        
        for view in subviews {
            view.removeFromSuperview()
        }
        // Drawing code
        scrollView = UIScrollView(frame:CGRect(x: 0,y: 2,width: rect.width, height: rect.height - 2))
        scrollView.isUserInteractionEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.isDirectionalLockEnabled = true
        scrollView.bounces = false
        scrollView.backgroundColor = .white
        var frame = CGRect(x: 0,y: 38, width: scrollView.frame.width, height: scrollView.frame.height - 40)

        pageControl = UIView(frame:CGRect(x: 0,y: 0, width: rect.width, height: 40))
        pageNum = views.count
        pageControl.backgroundColor = .white

        //创建菜单按钮下划线
        let label = UILabel(frame:CGRect(x: 0, y:pageControl.frame.height - 1, width: pageControl.frame.width, height: 1))
        label.backgroundColor = tabSelectedBgColor
        label.tag = 200

        let selectedLabel = UILabel(frame:CGRect(x: 0, y: pageControl.frame.height - 3, width: pageControl.frame.width / CGFloat(pageNum), height: 3))
        selectedLabel.backgroundColor = tabSelectedArrowBgColor
        selectedLabel.tag = 300

        if !showBottomLine {
            label.frame.size.height = 0
        }

        if !showSelectedBottomLine {
            selectedLabel.frame.size.height = 0
        }

        for i in 0..<views.count {
            var view = views[i]
            if view is UIViewController {
                view = (view as! UIViewController).view
            }
            frame.origin.x = rect.width * CGFloat(i)
            let type = view.self
            (view as! UIView).frame = frame
            scrollView.addSubview(view as! UIView)

            var pageFrame = pageControl.frame
            pageFrame.size.width = rect.size.width / CGFloat(pageNum)
            pageFrame.origin.x = pageFrame.width * CGFloat(i)

            //创建菜单按钮
            let button = UIButton(type: .custom)
            button.frame = pageFrame
            button.tag = 100 + i
            button.setTitleColor(tabTitleColor, for: .normal)
            button.setTitleColor(tabSelectedTitleColor, for: .selected)
            button.backgroundColor = tagBgColor
            button.setTitle(titleArray[i], for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 15)

            //创建菜单右侧小图标
            if titleIconsArray.count > 0 {
                button.setImage(titleIconsArray[i], for: .normal)
            }
            if selectedIconsArray.count > 0 {
                button.setImage(selectedIconsArray[i], for: .selected)
            }

            //创建菜单按钮右上角的小红点
            let x = getLabelWidth(string: titleArray[i] as NSString, fontSize: 15) / 2 + (button.titleLabel?.frame.origin.x)!
            let circleLabel = UILabel(frame:CGRect(x: x, y: 2, width: 16, height: 16))
            circleLabel.backgroundColor = .red
            circleLabel.textColor = .white
            circleLabel.font = UIFont.systemFont(ofSize: 12)
            circleLabel.textAlignment = .center
            circleLabel.tag = 600 + i
            circleLabel.layer.cornerRadius = 8
            circleLabel.layer.masksToBounds = true
            circleLabel.clipsToBounds = true
            
            if tipsCountArray.count == 0 {
                circleLabel.isHidden = true
            } else if tipsCountArray[i] <= 0 {
                circleLabel.isHidden = true
            } else {
                circleLabel.isHidden = false
                circleLabel.text = tipsCountArray[i] > 99 ? "99+" : "\(tipsCountArray[i])"
                let width = getLabelWidth(string: circleLabel.text as! NSString, fontSize: 12)
                circleLabel.frame.size.width = width > 16 ? width : 16
            }
            
            if showVLine {
                //创建中间分隔线
                let vlabel = UILabel(frame: CGRect(x: -1, y: 10, width: 1, height: button.frame.height - 20))
                vlabel.backgroundColor = tabArrowBgColor
                button .addSubview(vlabel)
                
                if i == 0 {
                    vlabel.isHidden = true
                }
            }
            
            if i == 0 {
                button.isSelected = true
            }
            
            if button.isSelected {
                UIView.animate(withDuration: 0.3, animations: { 
                    selectedLabel.frame.origin.x = button.frame.origin.x
                    button.backgroundColor = self.tabSelectedBgColor
                })
            }
            button.addSubview(circleLabel)
            pageControl.addSubview(button)
        }
        
        pageControl.addSubview(label)
        pageControl.addSubview(selectedLabel)
        
        if pageNum == 1 {
            pageControl.isHidden = true
        }
        
        if enableScroll {
            scrollView.contentSize = CGSize(width: rect.width * CGFloat(views.count + 1),
                                                 height: rect.height - 2)
        } else {
            scrollView.contentSize = CGSize.zero
        }
        scrollView.delegate = self
        addSubview(scrollView)
        addSubview(pageControl)
        
        scrollView.contentOffset = CGPoint.init(x: frame.width * CGFloat(selectedIndex),
                                                y: 0)
        let tmp = selectedIndex
        selectedIndex = tmp
    }

    func setIcons(title:[UIImage], selected:[UIImage]) {
        titleIconsArray = title
        selectedIconsArray = selected
        setNeedsDisplay()
    }

    func tabBtnClick(_ sender:UIButton) {
        let index = sender.tag - 100
        if showAnimation {
            UIView.beginAnimations("navTab", context: nil)
            UIView.setAnimationDuration(0.3)
            selectedIndex = index
            scrollView.contentOffset = CGPoint(x: CGFloat(index) * frame.width, y: 0)
            UIView.commitAnimations()
        } else {
            selectedIndex = index
            scrollView.contentOffset = CGPoint(x: CGFloat(index) * frame.width, y: 0)
        }
    }

    func getLabelWidth(string:NSString, fontSize:CGFloat) -> CGFloat {
        let stringSize = string.size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize)])
        return stringSize.width
    }
    
}

extension DJViewPager:UIScrollViewDelegate {
    public func  scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index = scrollView.contentOffset.x / frame.size.width
        selectedIndex = Int(index)
    }
}
